package cn.lyz.authority.system.service.impl;

import cn.lyz.authority.common.utils.JwtTokenUtil;
import cn.lyz.authority.system.dto.LoginUser;
import cn.lyz.authority.system.dto.LoginUserDTO;
import cn.lyz.authority.system.entity.SysUser;
import cn.lyz.authority.system.service.ISysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Service
public class SysLoginServiceImp implements ISysLoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public String login(LoginUserDTO user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        SysUser sysUser = loginUser.getUser();
        log.info("用户: {}",sysUser);
        //todo 缓存token到redis中
        return jwtTokenUtil.generateToken(sysUser.getUserName());
    }

    @Override
    public void logout(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        String[] s = authorization.split(" ");
        String token = s[1];
        //todo 缓存登出token到redis中
    }
}
